package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Set;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result addDish(DishDTO dto) {
        //保存菜品
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto,dish);
        dishMapper.insert(dish);

        //保存菜品与品味的关系
        List<DishFlavor> flavors = dto.getFlavors();
        if (!CollectionUtils.isEmpty(flavors)) {
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
            dishFlavorMapper.batchInsert(flavors);
        }
        //清理缓存
        redisTemplate.delete("dishes"+dto.getCategoryId());
        return  Result.success(flavors);
    }

    /**
     *
     * @param dto
     * @return
     */
    @Override
    public Result queryDishesByPage(DishPageQueryDTO dto) {
        //开启分页
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        //查询列表
        Page<DishVO> page = dishMapper.selectByPage(dto);
        //封装结果
        PageResult result = new PageResult(page.getTotal(),page.getResult());
        return Result.success(result);
    }

    /**
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public Result deleteDishesByIds(List<Long> ids) {
        //1. 如果ids对应的菜品里，有未停售的菜品，则不能删除
        int enableDishCount = dishMapper.selectEnableDishCountByIds(ids);
        if (enableDishCount > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //2. 如果ids对应的菜品里，有关联的套餐，则简单处理，直接不予删除
        int setmealCount = setmealDishMapper.selectSetmealCountByDishIds(ids);
        if (setmealCount > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品
        dishMapper.batchDeleteByIds(ids);
        //删除菜品对应的口味
        dishFlavorMapper.batchDeleteByDishIds(ids);

        //清理缓存
        Set<String> keys = redisTemplate.keys("dishes:*");
        redisTemplate.delete(keys);
        return Result.success();
    }

    /**
     * @param id
     * @return
     */
    @Override
    public Result queryDishById(Long id) {
        //根据id查询菜品信息
        Dish dish = dishMapper.selectById(id);
        //根据菜品id查询口味列表
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectByDishId(id);
        //封装结果
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);
        return Result.success(dishVO);
    }

    /**
     *
     * @param dto
     * @return
     */
    @Override
    public Result updateDishById(DishDTO dto) {
        //1.修改菜品信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto,dish);
        dishMapper.updateById(dish);
        //2. 删除菜品对应的原口味列表
        dishFlavorMapper.batchDeleteByDishIds(Collections.singletonList(dto.getId()));
        //3. 重新添加菜品的口味列表
        List<DishFlavor> flavors = dto.getFlavors();
        if (!CollectionUtils.isEmpty(flavors)) {
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dto.getId()));
            dishFlavorMapper.batchInsert(flavors);
        }
        redisTemplate.delete("dishes"+dto.getCategoryId());
        return Result.success(flavors);
    }

    /**
     * 根据分类id查询菜品列表
     * @param categoryId
     * @return
     */
    @Override
    public Result queryDishesByCategoryId(Long categoryId) {
        List<Dish> dishes = dishMapper.selectDishesByCategoryId(categoryId);
        return Result.success(dishes);
    }


    @Override
    public List<DishVO> queryUserDishesByCategoryId(Long categoryId) {
        //优先从Redis查询缓存的数据
        String jsonStr = redisTemplate.opsForValue().get("dishes" + categoryId);
        //如果查询到了，就直接返回缓存的结果
        if (jsonStr != null || "".equals(jsonStr)) {
            //需要把json格式字符串转换成java对象：FastJson
            return JSON.parseArray(jsonStr,DishVO.class);
        }
        //如果查不到再从数据库里边查
        //1. 查询菜品列表，及每个菜品关联的分类名称（查询起售状态的）
        List<DishVO> dishVOList = dishMapper.selectEnableListByCategoryId(categoryId);
        //2. 查询每个菜品关联的口味列表
        for (DishVO dishVO : dishVOList) {
            //根据菜品id查询对应的口味列表
            List<DishFlavor> dishFlavors = dishFlavorMapper.selectListByDishId(dishVO.getId());
            dishVO.setFlavors(dishFlavors);
        }
        //把数据缓存到Redis里边
        redisTemplate.opsForValue().set("dishes" + categoryId,JSON.toJSONString(dishVOList));
        return dishVOList;
    }

}
